<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BUISCreenCreateService
 *
 * @author jianfeng
 */
class BScreenCreateServiceMeta extends BUIScreen {

    private $serviceId = null;

    const TRANSIT_VARIABLE_NEWSERVICE = "NewService";
    const ACTION_NEXT = 'next';
    const ACTION_COMPLETE = "complete";

    //put your code here

    public function render($data = null) {
        
        /*
        
        $activeAppUI = Blyn::app()->getActiveServiceApp()->getUIManager();
        
        //remove serviceAppTopBar
        if(isset($activeAppUI->views['serviceAppTopBar']))
            unset($activeAppUI->views['serviceAppTopBar']);
         * 
         */
        //add new serviceAppTopBar for createService operation
        Blyn::app()->getActiveServiceApp()->getUIManager()->setRenderView(BUIServiceApp::View_ServiceAppTopBar, 'PersonalService_AppTopBar');

        $this->renderCreateService($data);

        //$this->startRender();
    }

    protected function getBootStrapFormMeta($data = NULL) {
        if (!is_array($data)) {
            $data = array();
        }

        //build bootstrap form meta
        $form = array('type' => 'vertical', 'id' => 'form_createServiceMeta');

        $items = array();
        $inputServiceName = array(
            'model' => $model,
            'type' => 'textField',
            'htmlOption' => array(
                'class' => 'span3',
                'name' => 'serviceName',
                'maxLength' => '32'
            )
        );
        array_push($items, $inputServiceName);
        $inputServiceCategory = array('model' => $model, 'modelField' => 'serviceCategory',
            array('class' => 'span3'));
        array_push($items, $inputServiceCategory);
        $inputServiceRole = array('model' => $model, 'modelField' => 'serviceRole',
            array('class' => 'span3'));
        array_push($items, $inputServiceRole);
        $inputServiceApps = array('model' => $model, 'modelField' => 'serviceApps',
            array('class' => 'span3'));
        array_push($items, $inputServiceApps);

        $form['items'] = $items;
    }

    protected function getActiveFormMeta($data = NULL) {
        
    }

    public function renderCreateService($data = null) {

        if (!is_array($data)) {
            $data = array();
        }

        $isRenderInitialView = true;

        //$form = $this->getFormByMeta('CreateService', $this);

        $model = new CreateServiceFormModel('CreateService');

        if (isset($_POST['CreateServiceFormModel'])) {
            $model->attributes = $_POST['CreateServiceFormModel'];
        }

        if ($this->isAjaxLinkClicked('nextBtn') && $model->validate()) {
            $service = $this->createServiceMeta($model);

            $isRenderInitialView = FALSE;

            $service->setVisible(FALSE);

            if ($this->isMemberOfScreenFlow())
                $this->getParent()->gotoScreen(BUIScreenFlow::NEXT);
        }
        /*
          if (isset($_POST['next']) && $model->validate()) {

          $service = $this->createServiceMeta($model);

          $isRenderInitialView = FALSE;

          $service->setVisible(FALSE);

          if ($this->isMemberOfScreenFlow())
          $this->getParent()->gotoScreen(BUIScreenFlow::NEXT);

          yii::app()->end();
          }
         * 
         */
      //  if (isset($_POST['cancel'])) {
        if ($this->isAjaxLinkClicked('cancelBtn')) {          
            $this->gotoUINode('home');
        }
        /*
          if (isset($_POST['complete']) && $model->validate()) {
          $service = $this->createServiceMeta($model);
          $this->gotoScreen('BScreenCreateServiceSummary', $data);
          $isRenderInitialView = FALSE;
          //yii::app()->end();
          }
         * 
         */
        if ($this->isAjaxLinkClicked('completeBtn') && $model->validate()) {
            $service = $this->createServiceMeta($model);
            $this->gotoScreen('BScreenCreateServiceSummary', $data);
            //$isRenderInitialView = FALSE;
            //yii::app()->end();
        }

        if ($isRenderInitialView) {
            $this->addRenderView('pageTitle', 'pagetitle', array('pageTitle' => 'Create Service With Meta'));
            $this->addRenderView('createServiceMeta', 'createServiceWithMeta', array('model' => $model, 'screen' => $this));
        }
    }

    private function createServiceMeta($model) {

        $serviceRole = $this->getDefaultServiceRole()->getId();
        if ($model->serviceRole != NULL)
            $serviceRole = $model->serviceRole;
        $serviceId = $this->createService($model->serviceName, $model->serviceCategory, $serviceRole, FALSE);
        $service = new BService($serviceId);
        $this->getUINode()->addTransitVariable(self::TRANSIT_VARIABLE_NEWSERVICE, $service);

        //add screenAction into BUICode
        $screenAction = new BUIScreenAction($this->getName(), self::ACTION_NEXT);
        $screenAction->addInputElement('ServiceName', $model->serviceName);

        $categoryData = $this->getServiceCategoryData();
        $categoryValue = $model->serviceCategory;
        $categoryDisplayValue = $categoryData[$categoryValue];
        $screenAction->addInputElement('ServiceCategory', $categoryValue, $categoryDisplayValue);

        $roleData = $this->getServiceRolesData();

        $screenAction->addInputElement('ServiceRole', $serviceRole, $roleData[$serviceRole]);

        $screenAction->setStatus(BUIScreenAction::STATUS_COMPLETED);
        $this->getUINode()->addScreenActionGroup('CreateServiceActions', $screenAction);

        return $service;
    }

    public function getServiceTypeData() {
        $data = CHtml::listData(BMServiceType::model()->findAll(), '_id', 'typename');
        return $data;
    }

    public function getServiceCategoryData() {
        $data = CHtml::listData(BMServiceCategory::model()->findAll(), '_id', 'categoryname');
        return $data;
    }

    public function getServiceApps() {
        $sql = "select * from bln_application where showable > 0";
        $data = CHtml::listData(BMApplication::model()->findAllBySql($sql), '_id', 'appname');

        $db = Blyn::app()->getAppDb();

        $typeApps = $db->getVisibleServiceApps(NULL, BService::NORMALSERVICETYPE);

        $data = CHtml::listData($typeApps, '_id', 'appname');
        return $data;
    }

    public function getServiceRolesData() {
        $serviceEngine = new BServiceEngine();
        $db = $serviceEngine->getDbAdapter();

        $roles = $db->getAppRoles($serviceEngine->getId());

        $data = array();

        foreach ($roles as $role) {
            $data[$role->getId()] = $role->getShowName();
        }

        return $data;
    }

    protected function getDefaultServiceRole() {
        $engine = new BServiceEngine();

        return $engine->getAuthManager()->getRole(BBasicRolesTemplate::SERVICE_ADMIN_ROLE);
    }

    protected function createService($name, $categoryId, $serviceRole = null, $visible = true, $appId = null) {
        $service = BService::createService(array('ServiceName' => $name, 'ServiceRole' => $serviceRole,
                    'ServiceCategoryId' => $categoryId, 'Visible' => $visible));

        if ($appId != null) {
            $app = BServiceApp::getInstanceById($appId);
            $app->addToService($service);
        }

        $this->serviceId = $service->getId();

        return $this->serviceId;
    }

}

?>
